package flc.ast.fragment;

import android.Manifest;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.StatFs;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ScreenUtils;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import flc.ast.R;
import flc.ast.activity.FileScanQrActivity;
import flc.ast.activity.FileTransferActivity;
import flc.ast.activity.HardwareInfoActivity;
import flc.ast.databinding.FragmentHomeBinding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.device.DeviceInfoUtil;
import stark.common.basic.device.StorageUtil;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.BroadcastReceiverUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> {

    private BroadcastReceiver broadcastReceiver;

    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.llDevice.setOnClickListener(this);
        mDataBinding.ivTransfer.setOnClickListener(this);
        mDataBinding.ivReceive.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llDevice://硬件信息
                startActivity(HardwareInfoActivity.class);
                break;
            case R.id.ivTransfer://文件传输
                getTransferPermission();
                break;
            case R.id.ivReceive://文件接收
                getReceivePermission();
                break;
        }
    }

    @Override
    protected void initData() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //获取当前电量
                int level = intent.getIntExtra("level", 0);
                mDataBinding.tvBattery.setText(getString(R.string.battery_text) + level + getString(R.string.unit_percent));
            }
        };
        BroadcastReceiverUtil.registerReceiver(mContext, broadcastReceiver, intentFilter);
        mDataBinding.tvDevice.setText(getString(R.string.current_device) + DeviceInfoUtil.getDeviceModel());//型
        mDataBinding.tvCpu.setText(getCpu());//cpu
        mDataBinding.tvMemory.setText(getRAMTotalMemorySize(mContext));//内存
        StatFs intStaFs = StorageUtil.getExternalMemory();
        mDataBinding.tvStorage.setText(ConvertUtils.byte2FitMemorySize(intStaFs.getTotalBytes(), 0));//存储
        mDataBinding.tvScreenResolution.setText(ScreenUtils.getScreenHeight() + "*" + ScreenUtils.getScreenWidth() + getString(R.string.pixel_text));//分辨率
    }

    //获取CPU
    public static String getCpu() {
        String str1 = "/proc/cpuinfo";
        String str2 = "";
        String cpuName = "";

        try {
            FileReader fileReader = new FileReader(str1);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            while ((str2 = bufferedReader.readLine()) != null) {
                if (TextUtils.isEmpty(str2)) {
                    continue;
                }
                String[] arrayOfString = str2.split(":\\s+", 2);
                if (TextUtils.equals(arrayOfString[0].trim(), "Hardware")) {
                    cpuName = arrayOfString[1];
                    break;
                }
            }

            bufferedReader.close();
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cpuName;
    }

    public static String getRAMTotalMemorySize(final Context context) {
        //获得ActivityManager服务的对象
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //获得MemoryInfo对象
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        //获得系统可用内存，保存在MemoryInfo对象上
        mActivityManager.getMemoryInfo(memoryInfo);
        long memSize = memoryInfo.totalMem;
        //字符类型转换
        String availMemStr = formateFileSize(context, memSize);
        return availMemStr;

    }

    //调用系统函数，字符串转换 long -String KB/MB
    public static String formateFileSize(Context context, long size) {
        return Formatter.formatFileSize(context, size);
    }

    private void getTransferPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_ALL_MEDIA, Manifest.permission.READ_CONTACTS)
                .reqPermissionDesc(getString(R.string.get_transfer_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(FileTransferActivity.class);
                    }
                }).request();
    }

    private void getReceivePermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_ALL_MEDIA, Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.CAMERA)
                .reqPermissionDesc(getString(R.string.get_receive_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        startActivity(FileScanQrActivity.class);
                    }
                }).request();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mContext.unregisterReceiver(broadcastReceiver);
    }

}